package com.javasm.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.javasm.entity.Users;
import com.javasm.service.UserService;
import com.javasm.utils.SpringUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author: Lisa
 * @className: MyUsernamePasswordFilter
 * @description:
 * @date: 2023/10/22 22:18
 * @VERSION: 0.1
 * @SINCE: jdk11
 */
public class MyUsernamePasswordFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                Map map = objectMapper.readValue(request.getInputStream(), Map.class);
                // 获取邮箱和验证码
                String email = map.get("email").toString();
                String code = map.get("code").toString();

                UserService userService = SpringUtil.getBean(UserService.class);
                RedisTemplate redisTemplate = SpringUtil.getBean("redisTemplate", RedisTemplate.class);
                String realCode = redisTemplate.opsForValue().get(email).toString();
                if (!realCode.equalsIgnoreCase(code)) throw new AuthenticationServiceException("验证码错误！");
                Users user = userService.findUserByEmail(email);

                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
                this.setDetails(request, authRequest);
                return this.getAuthenticationManager().authenticate(authRequest);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
